#include <iostream>

#include "command.hpp"

class Init
{
public:
    Init()
    {
        //利用管道传递数据
        bool r = MakeFifo();
        if (!r)
             return;
        // 创建key
        key_t key = Get_key();

        std::cout << "key : " << ToHex(key) << std::endl;

        // 创建共享内存
        shmid = CreateShm(key);

        std::cout << "shmid: " << shmid << std::endl;
        std::cout << "开始将shm映射到进程的地址空间中" << std::endl;

        // sleep(5);
        //  挂接共享内存
        s = (char *)shmat(shmid, nullptr, 0);

        fd = open(filename.c_str(), O_RDONLY);
    }
    ~Init()
    {
        // sleep(5);
        //  解连共享内存
        shmdt(s);
        std::cout << "开始将shm从进程的地址空间中移除" << std::endl;

        // sleep(3);
        //  删除共享内存
        shmctl(shmid, IPC_RMID, nullptr);
        std::cout << "开始将shm从OS中删除" << std::endl;
        // sleep(10);
        close(fd);
    }

public:
    int fd;
    int shmid;
    char *s;
};

int main()
{
    Init init;
    while (true)
    {
        int code = 0;
        ssize_t n = read(init.fd, &code, sizeof(code));
        if (n > 0)
        {
            std::cout << "共享内存的内容：" << init.s << std::endl;
            sleep(1);
        }
        else if (n == 0)
            break;
    }

    return 0;
}
